package com.ewing.core.auth.helper;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.ewing.common.constants.RedisKey;
import com.ewing.core.auth.SmsAuthCodeCache;
import com.ewing.core.redis.RedisException;
import com.ewing.core.redis.RedisManage;

/**
 * sms 验证码的缓存
 * 
 * @author Joeson
 */
public class SmsAuthCodeCacheHelper {

  private static final long DEFAULT_CACHE_TIME = 5 * 60 * 1000;

  private static Logger logger = Logger.getLogger(SmsAuthCodeCacheHelper.class);

  public static SmsAuthCodeCache getCache(String phone) {
    if (StringUtils.isEmpty(phone)) {
      return null;
    }

    try {
      return RedisManage.getInstance().get(RedisKey.SMS_AUTH_CODE + phone);
    } catch (RedisException e) {
      logger.error(e.getMessage(), e);
      return null;
    }
  }

  /**
   * 缓存是否超过时间
   * 
   * @param cacheTime
   * @return
   */
  public static boolean isExpire(Long cacheTime) {
    if (null == cacheTime) {
      return true;
    }

    return System.currentTimeMillis() - cacheTime > DEFAULT_CACHE_TIME;
  }

  public static boolean isValidCache(SmsAuthCodeCache cache) {
    if (null == cache || cache.getAuthCount() > 2 || isExpire(cache.getCacheTime())) {
      return false;
    }

    return true;
  }

  public static boolean set(String phone, String code) {
    if (StringUtils.isEmpty(phone)) {
      return false;
    }

    try {
      RedisManage.getInstance().set(RedisKey.SMS_AUTH_CODE + phone,
          new SmsAuthCodeCache(phone, code, 0), 180);

    } catch (RedisException e) {
      logger.error(e.getMessage(), e);
      return false;
    }

    return true;
  }


  public static void del(String phone) {
    if (StringUtils.isEmpty(phone)) {
      return;
    }

    try {
      RedisManage.getInstance().del(RedisKey.SMS_AUTH_CODE + phone);
    } catch (RedisException e) {
      logger.error(e.getMessage(), e);
    }
  }

  public static void incr(SmsAuthCodeCache cache) {
    if (null == cache) {
      return;
    }

    cache.setAuthCount(cache.getAuthCount() + 1);
    try {
      RedisManage.getInstance().set(RedisKey.SMS_AUTH_CODE + cache.getPhone(), cache);
    } catch (RedisException e) {
      logger.error(e.getMessage(), e);
    }
  }

  public static void authAuth(SmsAuthCodeCache cache) {
    if (null == cache) {
      return;
    }

    // 如果验证三次获取过期，要进行删除缓存操作
    if (null != cache && cache.getAuthCount() >= 2) {
      del(cache.getPhone());
    } else {
      incr(cache);
    }
  }



}
